import csv
import os
from math import nan

import chardet
import numpy as np

import matplotlib.pyplot as plt
import pandas as pd

# 设置字体以支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


def show(data, p85):
    # 提取数据
    keys = list(data.keys())
    mean_speeds = [d['count'] for d in data.values() if 'count' in d]

    # 创建图形和坐标轴
    fig, ax = plt.subplots()
    # 绘制柱状图
    bar_width = 0.35
    indices = np.arange(len(keys))

    # 第一组柱状图
    # rects = ax.bar(indices, mean_speeds, bar_width, label='Mean Speed')
    ax.plot(indices, mean_speeds, marker='o', linestyle='-', color='r', label='慢行车数量')
    # 绘制85分位数线
    plt.axhline(y=p85, color='b', linestyle='--', label='85分位线')

    # 在柱子上添加数据标签
    def add_labels(rects):
        for rect in rects:
            height = rect.get_height()
            ax.annotate('{}'.format(height),
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 3),  # 3 points vertical offset
                        textcoords="offset points",
                        ha='center', va='bottom')

    # add_labels(rects1)
    # add_labels(rects2)

    # 设置 x 轴的刻度和标签，每隔12个显示一次
    ticks = indices[::12]  # 每隔12个索引选取一个
    tick_labels = keys[::12]  # 对应的标签也每隔12个选取一个

    # 添加标签和标题
    ax.set_xlabel('时间')
    ax.set_ylabel('数量（辆）')
    ax.set_title('小客车全天慢行数量统计')
    ax.set_xticks(ticks)
    ax.set_xticklabels(tick_labels)
    ax.legend()

    # # 叠加折线图
    # diff = [d['flow_diff'] for d in data.values() if 'flow_diff' in d]
    # ax2 = ax.twinx()  # 创建第二个y轴
    # ax2.plot(indices, diff, marker='o', linestyle='-', color='r', label='Trend')
    # ax2.set_ylabel('Flow Diff')  # 我们假设这是趋势线的数据
    # ax2.legend(loc='upper right')

    # 显示图表
    plt.show()

def get_data(path):
    df_up = pd.read_csv(path)
    data0 = df_up.to_dict(orient='records')
    print(data0)
    data = {}
    value = []
    for i in range(len(data0)):
        time = data0[i]['time'].split(' ')[1][:5]
        data[time] = {
            "count": data0[i]['count']
        }
        value.append(data0[i]['count'])
    print(data)
    # 计算85分位数
    value = np.array(value)
    p85 = np.percentile(value, 85)
    return data, p85



if __name__ == '__main__':
    # # A区轻度1
    path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240131\car_slow_move_data.csv'
    # A区重度1
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240207\car_slow_move_data.csv'
    # A区重度2
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240219\car_slow_move_data.csv'
    dict_data, p85 = get_data(path)
    show(dict_data, p85)

